package com.lx.ngsl.core.login.service;

import java.util.List;

import javax.security.auth.login.LoginException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.lx.ngsl.core.user.entity.UserEntity;
import com.lx.ngsl.core.user.repository.UserRepository;
import com.lx.ngsl.util.Md5Util;

/*
 * 以用户名方式登录验证
 */
@Service
public class UsernameLoginAuth implements LoginAuth {

	@Autowired
	private UserRepository userRepository;
	
	
	@Override
	public UserEntity loginAuth(UserEntity user) throws LoginException {
		String username = user.getUsername();
		String password = user.getPassword();
		if(StringUtils.isEmpty(username)) {
			throw new LoginException("用户名不能为空！");
		}
		
		if(StringUtils.isEmpty(password)) {
			throw new LoginException("密码不能为空！");
		}
		
		List<UserEntity> userList = userRepository.findByUsername(username);
		if(userList == null || userList.size() == 0) {
			throw new LoginException("该用户不存在！");
		}
		
		user = userList.get(0);
		int status = user.getAccountState();
		String pwd = user.getPassword();
		if(status == 0 ) {
			throw new LoginException("该用户已被禁用！");
		}
		System.out.println(Md5Util.md5Str(password, "ngsl"));
		
		if(!Md5Util.md5Str(password, "ngsl").equals(pwd)) {
			throw new LoginException("密码错误！");
		}
		return user;
	}

	
}
